﻿<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>返回顶部效果</title>
    <link rel="stylesheet" href="https://cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <style type="text/css">
        body {
            margin: 0;
            padding: 0;
        }

        #returnTop {
            position: fixed;
            right: 50px;
            bottom: 100px;
        }
    </style>
    <script type="text/javascript">
        window.onload = function(){
            // 1.注册窗口滚动事件
            window.onscroll = function(){
                // 找到返回顶部的ICON
                var returnTopICON = document.getElementById("returnTop");
                //非IE滚动的距离
                //console.log(document.documentElement.scrollTop);
                //IE滚动的距离
                //console.log(document.body.scrollTop);

                // Math.max 取非IE和IE两个滚动距离的最大值
                var scrollDistance = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
                // 2. 滚动离顶部的距离大于300时，显示ICON
                if(scrollDistance > 300){
                    returnTopICON.style.display = 'block';
                }else{
                    returnTopICON.style.display = 'none';
                }
            }

            //3. 注册点击事件，返回顶部 ==>> 即设置scrollTop 的值为0
            var returnTopICON = document.getElementById("returnTop");
            returnTopICON.onclick = function(){
                // 直接设置为0，是没有过渡效果的
                // document.documentElement.scrollTop = 0;
                // document.body.scrollTop = 0;

                // 4. 用定时器做返回顶部的滚动效果
                var dsj = setInterval(function(){
                    var distance = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
                    distance -= 80;
                    if(distance <= 0){
                        //如果滚动的距离 <= 0 时，清除掉定时器，否则点击图标滚动到顶部后，不能往下拉，一拉就又滚动到顶部
                        clearInterval(dsj);
                    }else{
                        document.documentElement.scrollTop = distance;
                        document.body.scrollTop = distance;
                    }
                },40);

            }
        }
    </script>
</head>
<body>
    <div style="background: firebrick;height: 500px;">

    </div>
    <div style="height: 2000px;background: gainsboro">
        <p id="returnTop" style="display: none">
            <i class="fa fa-chevron-up fa-3x"></i>
        </p>
    </div>
</body>
</html>